package com.bt.dmdb.dao.impl;

import java.io.Serializable;
import javax.annotation.Resource;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.bt.dmdb.dao.GenericDao;

@Transactional(value = "txmDmdb", propagation = Propagation.MANDATORY)
public abstract class GenericDaoImpl<T, ID extends Serializable> implements GenericDao<T, ID> {

    @Resource(name = "sfDmdb")
    private SessionFactory sf;
    private Class<T> type;

    public GenericDaoImpl(Class<T> type) {
        this.type = type;
    }

    @Override
    @SuppressWarnings("unchecked")
    public ID insert(T t) {
        return (ID) cs().save(t);
    }

    @Override
    public T create(T t) {
        cs().save(t);
        return t;
    }

    @Override
    @SuppressWarnings("unchecked")
    @Transactional(value = "txmDmdb", readOnly = true)
    public T retreive(ID id) {
        return (T) cs().get(type, id);
    }

    @Override
    public void update(T t) {
        cs().update(t);
    }

    @Override
    public void delete(T t) {
        cs().delete(t);
    }

    protected Session cs() {
        return sf.getCurrentSession();
    }

    protected SessionFactory getSf() {
        return sf;
    }

    protected void setSf(SessionFactory sf) {
        this.sf = sf;
    }
}
